package com.example.tcp.server;

import com.example.tcp.server.mqtt.MqttFrame;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.mqtt.MqttMessage;

@ChannelHandler.Sharable
public class Handler extends SimpleChannelInboundHandler<Object> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Client.onChannelActive(ctx);
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Client.onChannelInactive(ctx);
        ctx.fireChannelInactive();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof Frame) { // 自定义报文格式
            ((Frame) msg).onRecv(ctx);
        } else if(msg instanceof MqttMessage) { // mqtt 报文格式
            new MqttFrame((MqttMessage) msg).onRecv(ctx);
        }
    }
}
